package info.nene_loveplus.controller.admin;

import info.nene_loveplus.model.Link;

import java.util.logging.Logger;

import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;
import org.slim3.util.IntegerUtil;
import org.slim3.util.StringUtil;

import com.google.appengine.api.datastore.KeyFactory;

public class LinkPostController extends AbstractAdminController {

	private Logger logger = Logger
			.getLogger(LinkPostController.class.getName());

	@Override
	public Navigation doRun() throws Exception {
		logger.fine("linkPost start");

		String[] keys = paramValues("key");
		String[] labels = paramValues("label");
		String[] urls = paramValues("url");
		String[] sortOrders = paramValues("sortOrder");

		for (int i = 0; i < keys.length; i++) {

			if (!StringUtil.isEmpty(labels[i]) && !StringUtil.isEmpty(urls[i])) {

				Link link = new Link();
				if (!StringUtil.isEmpty(keys[i])) {
					link.setKey(KeyFactory.stringToKey(keys[i]));
				}
				link.setLabel(labels[i]);
				link.setUrl(urls[i]);
				try {
					link.setSortOrder(IntegerUtil.toInteger(sortOrders[i]));
				} catch (Exception e) {
					link.setSortOrder(0);
				}
				Datastore.put(link);

			} else if (!StringUtil.isEmpty(keys[i])) {

				Datastore.delete(KeyFactory.stringToKey(keys[i]));

			}
		}

		return redirect("link");
	}
}
